package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.crm;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.CallApiRecordResponse;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmIf004Detail;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmIf004Request;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmIf004SDO;
import com.epoch.app.otsapplicationadaptersdk.crmv2.mncrmif004v2.dto.ExternalSyncCreatePromotionResponse;
import com.epoch.app.otsapplicationadaptersdk.crmv2.mncrmif004v2.dto.ImportExternalPromotionRequest;
import com.epoch.app.otsapplicationadaptersdk.crmv2.mncrmif004v2.service.MnCrmIf004V2Service;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MessageHeaderPassiveSDO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MnCrmIf004ImportRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermDataResponse;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTitleDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTitleDataResponse;
import com.epoch.app.crpricecenter.service.CrPriceCenterService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


/**
 * @author hanguo
 * @date 2021/10/12
 * @Description CRM请求平台同步促销活动创建
 */
@Component
@Primary
public class MnCrmIf004V2ServiceImpl implements MnCrmIf004V2Service {
    private static final Log log = Log.getLogger(MnCrmIf004V2Service.class);

    @Resource
    private CrPriceCenterService crPriceCenterService;

    private static final String DATA_SOURCE = "excel_import";
    
    @ProcessInvoker(remark = "MnCrmIf004V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    @Override
    public ExternalSyncCreatePromotionResponse externalSyncCreatePromotion(MnCrmIf004Request mnCrmIf004Request) {

        ExternalSyncCreatePromotionResponse externalSyncCreatePromotionResponse = new ExternalSyncCreatePromotionResponse();

        List<CallApiRecordResponse> callApiRecordResponses = Lists.newArrayList();

        MnCrmIf004SDO data = mnCrmIf004Request.getData();
        //同步活动抬头表数据
        if (Objects.nonNull(data)) {
            //追加消息头
            MessageHeaderPassiveSDO messageHeader = mnCrmIf004Request.getMessageHeader();
            if (Objects.nonNull(messageHeader)) {
                data.setMessageId(messageHeader.getMessageId());
                data.setDataSource(messageHeader.getSender());
            }
            SyncActivityTitleDataRequest syncActivityTitleDataRequest = new SyncActivityTitleDataRequest();
            BeanUtils.copyProperties(data, syncActivityTitleDataRequest);
            syncActivityTitleDataRequest.setActivityId(data.getPromotionId());
            syncActivityTitleDataRequest.setSalesOrganization(data.getSaleOrganizationCode());
            syncActivityTitleDataRequest.setSalesChannel(data.getChannelCode());
            syncActivityTitleDataRequest.setActivityNoteId(data.getNoteId());
            syncActivityTitleDataRequest.setActivityNoteName(data.getNoteDesc());
            syncActivityTitleDataRequest.setActivityFacadeCode(data.getActivityType());
            syncActivityTitleDataRequest.setClientId(SapAndCrmFieldDealUtils.generateIdField(data.getCustomerCode()));
            String applyTotalFee = data.getApplyTotalFee();
            if (StringUtils.isNotBlank(applyTotalFee)) {
                BigDecimal multiply = new BigDecimal(applyTotalFee.trim()).multiply(new BigDecimal(100));
                syncActivityTitleDataRequest.setApplyFee(multiply.setScale(2, RoundingMode.HALF_DOWN).longValue());
            }
            //syncActivityTitleDataRequest.setApplyFee(SapAndCrmFieldDealUtils.toLong(data.getApplyTotalFee()));
            syncActivityTitleDataRequest.setCurrency(data.getCurrency());
            syncActivityTitleDataRequest.setActivityStartDate(SapAndCrmFieldDealUtils.toDate(data.getBeginDate()));
            syncActivityTitleDataRequest.setActivityEndDate(SapAndCrmFieldDealUtils.toEndDate(data.getEndDate()));
            syncActivityTitleDataRequest.setOrderStartDate(SapAndCrmFieldDealUtils.toDate(data.getOrderBeginDate()));
            syncActivityTitleDataRequest.setOrderEndDate(SapAndCrmFieldDealUtils.toEndDate(data.getOrderEndDate()));
            syncActivityTitleDataRequest.setVerificationPattern(null);  //自定义字段
            syncActivityTitleDataRequest.setActivityStatus(data.getStatus());
            syncActivityTitleDataRequest.setControlByGroupFlag(data.getFlag());
            syncActivityTitleDataRequest.setOutlaySubject(null);    //缺失 todo...hanguo
            syncActivityTitleDataRequest.setStatusRemark(null);     //缺失 todo...hanguo
            syncActivityTitleDataRequest.setFeatures(JSONObject.toJSONString(data));
            SyncActivityTitleDataResponse syncActivityTitleDataResponse = crPriceCenterService.syncActivityTitleData(syncActivityTitleDataRequest);
            log.info("同步活动抬头表数据 result = {}", JSONObject.toJSONString(syncActivityTitleDataResponse));

            //同步数据后的结果封装
            CallApiRecordResponse callSyncActivityTitleDataResponse = new CallApiRecordResponse();
            callSyncActivityTitleDataResponse.setRequestBody(JSONObject.toJSONString(syncActivityTitleDataRequest));
            callSyncActivityTitleDataResponse.setOperateResult(syncActivityTitleDataResponse.getSuccess());
            callSyncActivityTitleDataResponse.setTableName("ofs_activity_title");
            callSyncActivityTitleDataResponse.setMessage(syncActivityTitleDataResponse.getMessage());
            callApiRecordResponses.add(callSyncActivityTitleDataResponse);
            if (!syncActivityTitleDataResponse.getSuccess()) {
                externalSyncCreatePromotionResponse.setSuccess(false);
                externalSyncCreatePromotionResponse.setMessage(syncActivityTitleDataResponse.getMessage());
            }

            if (CollectionUtils.isNotEmpty(data.getItems())) {
                List<MnCrmIf004Detail> mnCrmIf004DetailList = data.getItems();
                mnCrmIf004DetailList.forEach(item -> {
                    //设置消息头
                    SyncActivityTermDataRequest syncActivityTermDataRequest = new SyncActivityTermDataRequest();
                    BeanUtils.copyProperties(item, syncActivityTermDataRequest);
                    if (Objects.nonNull(messageHeader)) {
                        item.setMessageId(messageHeader.getMessageId());
                        item.setDataSource(messageHeader.getSender());
                    }

                    syncActivityTermDataRequest.setActivityId(item.getPromotionId());
                    syncActivityTermDataRequest.setActivityTermId(item.getPromotionLineId());
                    syncActivityTermDataRequest.setActivityDetailType(null);        //自定义字段
                    syncActivityTermDataRequest.setBusinessFormat(item.getBusinessState());
                    syncActivityTermDataRequest.setBrand(item.getBrand());
                    syncActivityTermDataRequest.setItemCategory(item.getCategory());
                    syncActivityTermDataRequest.setItemSubject(item.getItemSubject());
                    //syncActivityTermDataRequest.setSpecialOfferPrice(SapAndCrmFieldDealUtils.trimStr(item.getSpecialPrice()));
                    String specialPrice = item.getSpecialPrice();
                    if (StringUtils.isNotBlank(specialPrice)) {
                        BigDecimal multiply = new BigDecimal(specialPrice.trim()).multiply(new BigDecimal(100));
                        syncActivityTermDataRequest.setSpecialOfferPrice(multiply.setScale(2, RoundingMode.HALF_DOWN).stripTrailingZeros().toPlainString());
                    }
                    syncActivityTermDataRequest.setSalesUnit(item.getSaleUnit());
                    syncActivityTermDataRequest.setItemId(SapAndCrmFieldDealUtils.generateIdField(item.getMaterialCode()));
                    syncActivityTermDataRequest.setItemQuantity(SapAndCrmFieldDealUtils.toInteger(item.getQuantity()));
                    syncActivityTermDataRequest.setGiftId(SapAndCrmFieldDealUtils.generateIdField(item.getGiftCode()));
                    syncActivityTermDataRequest.setGiftQuantity(SapAndCrmFieldDealUtils.toInteger(item.getGiftQuantity()));
                    syncActivityTermDataRequest.setFacadeDescription(item.getSpecification());
                    //syncActivityTermDataRequest.setApplyFee(SapAndCrmFieldDealUtils.toLong2(item.getApplyFee()));
                    String applyFee = item.getApplyFee();
                    if (StringUtils.isNotBlank(applyFee)) {
                        BigDecimal multiply = new BigDecimal(applyFee.trim()).multiply(new BigDecimal(100));
                        syncActivityTermDataRequest.setApplyFee(multiply.setScale(2, RoundingMode.HALF_DOWN).longValue());
                    }
                    syncActivityTermDataRequest.setApplyItemQuantity(SapAndCrmFieldDealUtils.toInteger(item.getPromotionQuantity()));
                    syncActivityTermDataRequest.setCurrency(item.getCurrency());
                    syncActivityTermDataRequest.setIntensityOfActivityDesc(item.getActivityExplain());
                    syncActivityTermDataRequest.setHeadQuartersInvestMoney(SapAndCrmFieldDealUtils.toLong2(item.getHeadInputAmount()));
                    syncActivityTermDataRequest.setCompanySelfInvestMoney(SapAndCrmFieldDealUtils.toLong2(item.getInputAmount()));
                    syncActivityTermDataRequest.setGradeQuantity(null);//缺失等级数量 todo...hanguo
                    syncActivityTermDataRequest.setStatus(data.getStatus() == null ? null : Integer.parseInt(data.getStatus()));

                    String activityOccupyQuantity = item.getActivityOccupyQuantity();
                    if (StringUtils.isNotBlank(activityOccupyQuantity)) {
                        syncActivityTermDataRequest.setActivityOccupyQuantity(SapAndCrmFieldDealUtils.toInteger(activityOccupyQuantity));
                    } else {
                        syncActivityTermDataRequest.setActivityOccupyQuantity(0);    //缺失活动占用量,默认为0
                    }
                    String occupyFee = item.getActivityOccupyFee();
                    if (StringUtils.isNotBlank(occupyFee)) {
                        BigDecimal multiply = new BigDecimal(occupyFee.trim()).multiply(new BigDecimal(100));
                        syncActivityTermDataRequest.setActivityOccupyFee(multiply.setScale(2, RoundingMode.HALF_DOWN).longValue());
                    } else {
                        syncActivityTermDataRequest.setActivityOccupyFee(0L);
                    }

                    //syncActivityTermDataRequest.setActivityOccupyFee(SapAndCrmFieldDealUtils.toLong());//缺失活动占用金额，默认为0
                    syncActivityTermDataRequest.setFeatures(JSONObject.toJSONString(item));
                    SyncActivityTermDataResponse syncActivityTermDataResponse = crPriceCenterService.syncActivityTermData(syncActivityTermDataRequest);
                    log.info("同步活动项目表数据 result = {}", JSONObject.toJSONString(syncActivityTermDataResponse));

                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncActivityTermDataResponse = new CallApiRecordResponse();
                    callSyncActivityTermDataResponse.setRequestBody(JSONObject.toJSONString(syncActivityTermDataRequest));
                    callSyncActivityTermDataResponse.setOperateResult(syncActivityTermDataResponse.getSuccess());
                    callSyncActivityTermDataResponse.setTableName("ofs_activity_term");
                    callSyncActivityTermDataResponse.setMessage(syncActivityTermDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncActivityTermDataResponse);
                    if (!syncActivityTermDataResponse.getSuccess()) {
                        externalSyncCreatePromotionResponse.setSuccess(false);
                        externalSyncCreatePromotionResponse.setMessage(syncActivityTermDataResponse.getMessage());
                    }

                });

            }
            log.info("MnCrmIf004ServiceImpl_externalSyncUpdatePromotionActivity => 执行结束修改结果 = {}", JSONObject.toJSONString(callApiRecordResponses));

            //如果没有执行出错的记录
            if (StringUtils.isBlank(externalSyncCreatePromotionResponse.getMessage()) && Objects.isNull(externalSyncCreatePromotionResponse.getSuccess())) {
                externalSyncCreatePromotionResponse.setSuccess(true);
            }
        }

        return externalSyncCreatePromotionResponse;
    }

    /**
     * 导入未清活动
     *
     * @param importExternalPromotionRequest
     * @return
     */
    @Override
    @ProcessInvoker
    public Result<List<MnCrmIf004ImportRequest>> importExternalPromotion(ImportExternalPromotionRequest importExternalPromotionRequest) {
        List<MnCrmIf004ImportRequest> request = importExternalPromotionRequest.getRequest();
        if (CollectionUtils.isEmpty(request)) {
            return Result.success(Lists.newArrayList());
        }
        //校验必传参数
        List<MnCrmIf004ImportRequest> checkRequestList = new ArrayList<>();
        for (MnCrmIf004ImportRequest mnCrmIf004ImportRequest : request) {
//            // todo 这里校验必填参数
//            if (Strings.isBlank(mnCrmIf004ImportRequest.getMaterialCode())) {
//                mnCrmIf004ImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-023", null).getDisplayErrorMessage());
//                continue;
//            }

            MnCrmIf004Request mnCrmIf004Request = convertToMnCrmIf004Request(mnCrmIf004ImportRequest);
            MessageHeaderPassiveSDO messageHeaderPassiveSDO = new MessageHeaderPassiveSDO();
            messageHeaderPassiveSDO.setMessageId(UUID.randomUUID().toString());
            messageHeaderPassiveSDO.setSender(DATA_SOURCE);
            mnCrmIf004Request.setMessageHeader(messageHeaderPassiveSDO);
            // 同步接口调用
            log.info("促销活动同步接口调用入参{}", JSONObject.toJSONString(mnCrmIf004Request));
            try {
                this.externalSyncCreatePromotion(mnCrmIf004Request);
            } catch (Exception e) {
                log.error("促销活动同步接口异常", e);
                mnCrmIf004ImportRequest.setErrorMessage(e.getMessage());
                continue;
            }
            checkRequestList.add(mnCrmIf004ImportRequest);
        }
        return Result.success(checkRequestList);
    }

    @NotNull
    private MnCrmIf004Request convertToMnCrmIf004Request(MnCrmIf004ImportRequest mnCrmIf004ImportRequest) {
        // 参数映射
        MnCrmIf004Request mnCrmIf004Request = new MnCrmIf004Request();
        MnCrmIf004SDO data = new MnCrmIf004SDO();
        MnCrmIf004Detail mnCrmIf004Detail = new MnCrmIf004Detail();
        List<MnCrmIf004Detail> items = new ArrayList<>();

        data.setSaleOrganizationCode(mnCrmIf004ImportRequest.getSaleOrganizationCode());
        data.setChannelCode(mnCrmIf004ImportRequest.getChannelCode());
        data.setPromotionId(mnCrmIf004ImportRequest.getPromotionId());
        mnCrmIf004Detail.setPromotionId(mnCrmIf004ImportRequest.getPromotionId());
        mnCrmIf004Detail.setPromotionLineId(mnCrmIf004ImportRequest.getPromotionLineId());
        data.setNoteId(mnCrmIf004ImportRequest.getNoteId());
        data.setNoteDesc(mnCrmIf004ImportRequest.getNoteDesc());
        data.setActivityType(mnCrmIf004ImportRequest.getActivityType());
        data.setCustomerCode(mnCrmIf004ImportRequest.getCustomerCode());
//        mnCrmIf004Detail.setCustomerName(mnCrmIf004ImportRequest.getCustomerName());
        data.setOrderBeginDate(mnCrmIf004ImportRequest.getOrderBeginDate());
        data.setOrderEndDate(mnCrmIf004ImportRequest.getOrderEndDate());
        data.setBeginDate(mnCrmIf004ImportRequest.getOrderBeginDate());
        data.setEndDate(mnCrmIf004ImportRequest.getOrderEndDate());
        data.setConsumeMethod(mnCrmIf004ImportRequest.getConsumeMethod());
        data.setStatus(mnCrmIf004ImportRequest.getStatus());
        mnCrmIf004Detail.setMaterialCode(mnCrmIf004ImportRequest.getMaterialCode());
//        mnCrmIf004Detail.setMaishu(mnCrmIf004ImportRequest.getMaishu());
        mnCrmIf004Detail.setGiftCode(mnCrmIf004ImportRequest.getGiftCode());
        mnCrmIf004Detail.setGiftQuantity(mnCrmIf004ImportRequest.getGiftQuantity());
        mnCrmIf004Detail.setSpecialPrice(mnCrmIf004ImportRequest.getSpecialPrice());
        mnCrmIf004Detail.setSaleUnit(mnCrmIf004ImportRequest.getSaleUnit());
        mnCrmIf004Detail.setSpecification(mnCrmIf004ImportRequest.getSpecification());
        mnCrmIf004Detail.setActivityExplain(mnCrmIf004ImportRequest.getActivityExplain());
        mnCrmIf004Detail.setQuantity(mnCrmIf004ImportRequest.getMaishu());
//        mnCrmIf004Detail.setPromotionQuantitye(mnCrmIf004ImportRequest.getPromotionQuantity());
        mnCrmIf004Detail.setPromotionQuantity(mnCrmIf004ImportRequest.getPromotionQuantity());
        mnCrmIf004Detail.setApplyFee(mnCrmIf004ImportRequest.getApplyFee());
//        mnCrmIf004Detail.setActivityOccupyQuantity(mnCrmIf004ImportRequest.getActivityOccupyQuantity());
//        mnCrmIf004Detail.setActivityOccupyFee(mnCrmIf004ImportRequest.getActivityOccupyFee());
        mnCrmIf004Detail.setHeadInputAmount(mnCrmIf004ImportRequest.getHeadInputAmount());
        mnCrmIf004Detail.setInputAmount(mnCrmIf004ImportRequest.getInputAmount());
//        mnCrmIf004Detail.setActivitySurplusQuantity(mnCrmIf004ImportRequest.getActivitySurplusQuantity());
//        mnCrmIf004Detail.setActivitySurplusAmount(mnCrmIf004ImportRequest.getActivitySurplusAmount());
//        mnCrmIf004Detail.setBusinessSurplusQuantity(mnCrmIf004ImportRequest.getBusinessSurplusQuantity());
        mnCrmIf004Detail.setBusinessState(mnCrmIf004ImportRequest.getBusinessState());
        mnCrmIf004Detail.setBrand(mnCrmIf004ImportRequest.getBrand());
        mnCrmIf004Detail.setCategory(mnCrmIf004ImportRequest.getCategory());
        mnCrmIf004Detail.setItemSubject(mnCrmIf004ImportRequest.getItemSubject());
        mnCrmIf004Detail.setActivityOccupyQuantity(mnCrmIf004ImportRequest.getActivityOccupyQuantity());
        mnCrmIf004Detail.setActivityOccupyFee(mnCrmIf004ImportRequest.getActivityOccupyFee());
        mnCrmIf004Detail.setActivityRemainingQuantity(mnCrmIf004ImportRequest.getActivitySurplusQuantity());
        mnCrmIf004Detail.setActivityRemainingFee(mnCrmIf004ImportRequest.getActivitySurplusAmount());
        mnCrmIf004Detail.setHeadInputRemainingFee(mnCrmIf004ImportRequest.getBusinessSurplusQuantity());

//        mnCrmIf004Detail.setSyncTime(mnCrmIf004ImportRequest.getSyncTime());
        items.add(mnCrmIf004Detail);
        data.setItems(items);
        mnCrmIf004Request.setData(data);

        return mnCrmIf004Request;
    }
}
